import numpy as np
from scipy.linalg import svd
from PIL import Image
import matplotlib.pyplot as plt

# 取前k个特征，对图像进行还原
def get_image_feature(s, k):
	# 对于S，只保留前K个特征值
	s_temp = np.zeros(s.shape[0])
	s_temp[0:k] = s[0:k]
	s = s_temp * np.identity(s.shape[0])
	# 用新的s_temp，以及p,q重构A
	temp = np.dot(p,s)
	temp = np.dot(temp,q)
	plt.imshow(temp, cmap=plt.cm.gray, interpolation='nearest')
	plt.show()
	print(A-temp)


# 加载256色图片
image = Image.open('./1280_720.JPG')
A = np.array(image)

#RGB三通道数据转换为灰度图
A[:,:,0] = A[:,:,1] = A[:,:,2] = (A[:,:,0] * 0.3 + A[:,:,1] * 0.59 + A[:,:,2] * 0.11)
#去掉第3个维度
A = A[:,:,0]
# 显示原图像
plt.imshow(A, cmap=plt.cm.gray, interpolation='nearest')
plt.show()
# 对图像矩阵A进行奇异值分解，得到p,s,q
#p:左奇异值矩阵，s:奇异值，q：右奇异值矩阵
p,s,q = svd(A, full_matrices=False)

print(s.shape)
# 取前k个特征，对图像进行还原
get_image_feature(s, int(s.shape[0]*0.01))  #1%
get_image_feature(s, int(s.shape[0]*0.1))  #10%
get_image_feature(s, int(s.shape[0]*0.2))   #20%
get_image_feature(s, int(s.shape[0]*0.5))   #50%

